import axios from 'axios';

export class N8nClient {
  constructor(baseURL, apiKey) {
    this.baseURL = baseURL;
    this.apiKey = apiKey;
    
    this.client = axios.create({
      baseURL: this.baseURL,
      headers: {
        'Content-Type': 'application/json',
        ...(apiKey && { 'X-N8N-API-KEY': apiKey })
      },
      timeout: 10000
    });

    this.client.interceptors.response.use(
      response => response,
      error => {
        const message = error.response?.data?.message || error.message || '未知错误';
        throw new Error(`N8N API错误: ${message}`);
      }
    );
  }

  async getWorkflows(activeOnly = false) {
    try {
      const params = {};
      if (activeOnly) {
        params.filter = JSON.stringify({ active: true });
      }
      
      const response = await this.client.get('/api/v1/workflows', { params });
      return response.data.data || [];
    } catch (error) {
      throw new Error(`获取工作流失败: ${error.message}`);
    }
  }

  async getWorkflow(id) {
    try {
      const response = await this.client.get(`/api/v1/workflows/${id}`);
      return response.data;
    } catch (error) {
      throw new Error(`获取工作流 ${id} 失败: ${error.message}`);
    }
  }

  async createWorkflow(workflowData) {
    try {
      const payload = {
        name: workflowData.name,
        nodes: workflowData.nodes || [],
        connections: workflowData.connections || {},
        active: workflowData.active || false,
        settings: workflowData.settings || {}
      };

      const response = await this.client.post('/api/v1/workflows', payload);
      return response.data;
    } catch (error) {
      throw new Error(`创建工作流失败: ${error.message}`);
    }
  }

  async executeWorkflow(id, data = {}) {
    try {
      const response = await this.client.post(`/api/v1/workflows/${id}/execute`, { data });
      return response.data;
    } catch (error) {
      throw new Error(`执行工作流 ${id} 失败: ${error.message}`);
    }
  }

  async deleteWorkflow(id) {
    try {
      await this.client.delete(`/api/v1/workflows/${id}`);
      return true;
    } catch (error) {
      throw new Error(`删除工作流 ${id} 失败: ${error.message}`);
    }
  }

  async testConnection() {
    try {
      await this.client.get('/api/v1/workflows?limit=1');
      return { success: true, message: '连接成功' };
    } catch (error) {
      return { success: false, message: `连接失败: ${error.message}` };
    }
  }
}